package cn.b.sky.mes.mm.controller;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.b.sky.mes.mm.model.InventoryAlarmRecipient;
import cn.b.sky.mes.mm.model.Tree;
import cn.b.sky.mes.mm.model.condition.InventoryAlarmRecipientCondition;
import cn.b.sky.mes.mm.service.InventoryAlarmRecipientService;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.user.controller.SecurityController;

@Controller
@RequestMapping(value = "/inventoryAlarmRecipient/*")
public class InventoryAlarmRecipientController extends SecurityController {

  private static final String INVENTORY_ALARM_RECIPIENT_LIST_PAGE = "mm/inventoryAlarmRecipient/recipient_list";

  private static final String INVENTORY_ALARM_RECIPIENT_PAGE = "mm/inventoryAlarmRecipient/recipientInfo";

  @Autowired
  InventoryAlarmRecipientService inventoryAlarmRecipientService;

  @RequestMapping("recipient_list")
  public String selectRecipientListByCondition(String navTabId, Model model) {
    model.addAttribute("navTabId", navTabId);
    return INVENTORY_ALARM_RECIPIENT_LIST_PAGE;
  }

  @RequestMapping("selectRecipientList")
  @ResponseBody
  public DWZResult selectRecipientListByCondition(InventoryAlarmRecipientCondition condition) {
    if (StringUtils.isEmpty(condition.getSiteCode())) {
      condition.setSiteCode(getSiteCode());
    }
    List<InventoryAlarmRecipient> list = inventoryAlarmRecipientService
        .selectInventoryAlarmRecipientListByCondition(condition);
    int count = inventoryAlarmRecipientService.selectInventoryAlarmRecipientCountByCondition(condition);
    condition.setTotalCount(count);
    condition.setData(list);
    return ajaxDone(condition);
  }

  @RequestMapping("addRecipient")
  public String addRecipient(String navTabId, Model model) {
    model.addAttribute("pattern", "add");
    bindModel(navTabId, model, null, null, null, false, false);
    return INVENTORY_ALARM_RECIPIENT_PAGE;
  }

  @RequestMapping("modifyRecipients")
  public String modifyRecipients(String navTabId, Model model, String userCode, String storageLocationCode,
      String materialCode, boolean hasWarehouse, boolean hasMaterialType) {
    model.addAttribute("pattern", "modify");
    bindModel(navTabId, model, userCode, storageLocationCode, materialCode, hasWarehouse, hasMaterialType);
    return INVENTORY_ALARM_RECIPIENT_PAGE;
  }

  @RequestMapping("viewRecipients")
  public String viewRecipients(String navTabId, Model model, String userCode, String storageLocationCode,
      String materialCode, boolean hasWarehouse, boolean hasMaterialType) {
    model.addAttribute("pattern", "view");
    bindModel(navTabId, model, userCode, storageLocationCode, materialCode, hasWarehouse, hasMaterialType);
    return INVENTORY_ALARM_RECIPIENT_PAGE;
  }

  private void bindModel(String navTabId, Model model, String userCode, String storageLocationCode,
      String materialCode, boolean hasWarehouse, boolean hasMaterialType) {
    model.addAttribute("navTabId", navTabId);
    model.addAttribute("userCode", userCode);
    model.addAttribute("storageLocationCode", storageLocationCode);
    model.addAttribute("materialCode", materialCode);
    List<Tree> warehouseTrees = inventoryAlarmRecipientService.selectWarehouseTrees(getSiteCode());
    List<Tree> materialTypeTrees = inventoryAlarmRecipientService.selectMaterialTypeTrees(getSiteCode());
    for (Tree tree : warehouseTrees) {
      for (Tree childTree : tree.getChildren()) {
        childTree.setChildren(materialTypeTrees);
      }
    }
    model.addAttribute("warehouseTrees", warehouseTrees);
    model.addAttribute("materialTypeTrees", materialTypeTrees);
    model.addAttribute("hasWarehouse", hasWarehouse);
    model.addAttribute("hasMaterialType", hasMaterialType);
    if (!StringUtils.isEmpty(userCode)) {
      List<InventoryAlarmRecipient> recipients = inventoryAlarmRecipientService.getInventoryAlarmRecipient(
          getSiteCode(), userCode, storageLocationCode, materialCode, hasWarehouse, hasMaterialType);
      model.addAttribute("recipients", recipients);
      if (!recipients.isEmpty()) {
        model.addAttribute("recipient", recipients.get(0));
        model.addAttribute("userText", recipients.get(0).getUserText());
      }
    }
  }

  @RequestMapping("checkRecipients")
  @ResponseBody
  public DWZResult checkRecipients(String userCode, String storageLocationCode, String materialCode,
      boolean hasWarehouse, boolean hasMaterialType) {
    List<InventoryAlarmRecipient> recipients = inventoryAlarmRecipientService.getInventoryAlarmRecipient(getSiteCode(),
        userCode, storageLocationCode, materialCode, hasWarehouse, hasMaterialType);
    return ajaxDone(recipients);
  }

  @RequestMapping("saveRecipients")
  @ResponseBody
  public DWZResult saveRecipients(String navTabId, String userCode, String storageLocationCode, String materialCode,
      String selectedWarehouseAndMaterialTypes, String selectedWarehouses, String selectedMaterialTypes, int lockFlag,
      boolean hasWarehouse, boolean hasMaterialType) {
    List<InventoryAlarmRecipient> list = new LinkedList<InventoryAlarmRecipient>();
    InventoryAlarmRecipient recipient;
    if (!StringUtils.isEmpty(selectedWarehouseAndMaterialTypes) || !StringUtils.isEmpty(selectedWarehouses)) {
      if (!StringUtils.isEmpty(selectedWarehouseAndMaterialTypes)) {
        for (String key : selectedWarehouseAndMaterialTypes.split(",")) {
          recipient = new InventoryAlarmRecipient();
          setInventoryAlarmRecipient(recipient, userCode, storageLocationCode, key.split(";")[0], key.split(";")[1],
              materialCode, lockFlag);
          list.add(recipient);
        }
      }
      if (!StringUtils.isEmpty(selectedWarehouses)) {
        for (String warehouseCode : selectedWarehouses.split(",")) {
          recipient = new InventoryAlarmRecipient();
          setInventoryAlarmRecipient(recipient, userCode, storageLocationCode, warehouseCode, null, materialCode,
              lockFlag);
          list.add(recipient);
        }
      }
    } else if (!StringUtils.isEmpty(selectedMaterialTypes)) {
      for (String materialTypeCode : selectedMaterialTypes.split(",")) {
        recipient = new InventoryAlarmRecipient();
        setInventoryAlarmRecipient(recipient, userCode, storageLocationCode, null, materialTypeCode, materialCode,
            lockFlag);
        list.add(recipient);
      }
    } else {
      recipient = new InventoryAlarmRecipient();
      setInventoryAlarmRecipient(recipient, userCode, storageLocationCode, null, null, materialCode, lockFlag);
      list.add(recipient);
    }
    inventoryAlarmRecipientService.deleteInventoryAlarmRecipient(getSiteCode(), userCode, storageLocationCode,
        materialCode, hasWarehouse, hasMaterialType);
    for (InventoryAlarmRecipient inventoryAlarmRecipient : list) {
      inventoryAlarmRecipientService.insertInventoryAlarmRecipient(inventoryAlarmRecipient);
    }
    return dialogAjaxDone(getImeViewMessageI18n(null, "successfulOperation.M"), navTabId, null, null, null);
  }

  @RequestMapping("deleteInventoryAlarmRecipient")
  @ResponseBody
  public DWZResult deleteInventoryAlarmRecipient(String navTabId, HttpServletRequest request) {
    String ids = request.getParameter("ids");
    if (StringUtils.isBlank(ids)) {
      return ajaxError(getImeViewMessageI18n(null, "parameterNull.M"));
    }

    String[] idArr = ids.split(",");
    BatchJobReport[] reports = new BatchJobReport[idArr.length];
    int failures = 0;
    for (int i = 0; i < idArr.length; i++) {
      reports[i] = inventoryAlarmRecipientService.deleteInventoryAlarmRecipient(Long.valueOf(idArr[i]));
      if (!reports[i].isSuccess()) {
        failures += 1;
      }
    }

    if (failures == 0) {
      return navTabAjaxDone(navTabId, null, null, null, getImeViewMessageI18n(null, "successfulOperation.M"), null);
    } else {
      return batchjobAjaxDone(request, Arrays.asList(reports));
    }
  }

  private void setInventoryAlarmRecipient(InventoryAlarmRecipient recipient, String userCode,
      String storageLocationCode, String warehouseCode, String materialTypeCode, String materialCode, int lockFlag) {
    if (!StringUtils.isEmpty(userCode)) {
      recipient.setUserCode(userCode);
    }
    if (!StringUtils.isEmpty(storageLocationCode)) {
      recipient.setStorageLocationCode(storageLocationCode);
    }
    if (!StringUtils.isEmpty(warehouseCode)) {
      recipient.setWarehouseCode(warehouseCode);
    }
    if (!StringUtils.isEmpty(materialTypeCode)) {
      recipient.setMaterialTypeCode(materialTypeCode);
    }
    if (!StringUtils.isEmpty(materialCode)) {
      recipient.setMaterialCode(materialCode);
    }
    recipient.setSiteCode(getSiteCode());
    recipient.setLockFlag(lockFlag);
    setCreateInfo(recipient);
  }

}
